package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;

import com.fsd.core.util.*;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.bean.CheckTree;
import com.fsd.core.bean.Tree;
import com.fsd.core.common.BusinessException;
import com.fsd.admin.model.A_Branch;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.service.A_BranchService;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.dao.A_BranchDao;
import com.fsd.admin.entity.A_LoginInfo;
import com.google.gson.Gson;

@Repository("A_BranchServiceImpl")
public class A_BranchServiceImpl extends MainServiceImpl<A_Branch, String> implements A_BranchService{

	private String depict = "机构";
	
    @Resource(name = "A_BranchDaoImpl")
	public void setBaseDao(A_BranchDao A_BranchDao) {
		super.setBaseDao(A_BranchDao);
	}
	
	@Resource(name = "A_BranchDaoImpl")
	private A_BranchDao objectDao;
	
    @Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService employeeService;
	
	/**
     * 状态启用
     */
	public static final String jgztqy1 = "a_jgztqy";
	public static final String jgztqy2 = "启用";
	/**
     * 状态停用
     */
	public static final String jgztty1 = "a_jgztty";
	public static final String jgztty2 = "停用";

	private static final Lock lock = new ReentrantLock();

	/**
	 * 栏目递回创建
	 * @param object
	 * @param objList
	 */
	private void getObjectStruct(A_Branch object, List<A_Branch> objList){
		for (A_Branch obj : objList) {
			if(object.getId().equals(obj.getParentid())){
				object.getList().add(obj);
				if (!Boolean.valueOf(obj.getIsleaf()))
					this.getObjectStruct(obj, objList);
			}
		}
	}
	/**
	 * 获取栏目结构
	 * @param id
	 * @return
	 */
	public A_Branch getObjectStructByID(String id, String companyid){
		lock.lock();
		Map<String, A_Branch> objectMap = null;
		String strKey = Config.BRANCHMAP + companyid;
		try {
			if(EhcacheUtil.getInstance().get(strKey) == null){
				List<A_Branch> allObjectList = objectDao.queryByHql(
						"from A_Branch t where t.companyid = '" + companyid + "' and t.deleted = '0' order by t.sort asc");
				objectMap = new HashMap<String, A_Branch>();
				List<A_Branch> objectList = new ArrayList<A_Branch>();
				List<A_Branch> objList = new ArrayList<A_Branch>();
				for (A_Branch obj : allObjectList) {
					objectMap.put(obj.getId(), obj);
				}
				A_Branch fobj = new A_Branch();
				fobj.setId(companyid);
				fobj.setCompanyid(companyid);
				fobj.setParentid(companyid);
				objectMap.put(fobj.getId(), fobj);
				this.getObjectStruct(fobj, allObjectList);
				EhcacheUtil.getInstance().put(strKey, objectMap);
			}else{
				objectMap = (Map<String, A_Branch>)EhcacheUtil.getInstance().get(strKey);
			}
		} finally {
			lock.unlock();
		}
		if (objectMap != null && objectMap.containsKey(id))
			return objectMap.get(id);
		else
			return null;
	}
	
	
	
	private String checkLeaf(String fid){
		long num = objectDao.getCount("parentid = '"+ fid +"'", "deleted = '0'");
		if (num > 0)
			return "false";
		return "true";
	}
	
	private List<A_Branch> queryObjectListById(String fid){
		return objectDao.queryByHql("from A_Branch a where a.parentid = '"+ fid +"' and a.deleted = '0' order by sort asc");
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("sort"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				c.add(Restrictions.eq("parentid", objectMap.get("fid")));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTree(String fid, boolean isQuery, A_Employee employee) throws Exception{
		A_Branch branch = this.getObjectStructByID(fid, employee.getCompanyid());
		List<Tree> treelist = new ArrayList<Tree>();
		if (branch != null && branch.getList() != null && branch.getList().size() > 0){
			Tree tree = null;
			A_Branch obj = null;
			for (Object o : branch.getList()) {
				obj = (A_Branch)o;
				if (!isQuery && !obj.getStatuscode().equals(jgztqy1))
					continue;
				tree = new Tree();
				tree.setId(obj.getId());
				tree.setText(obj.getName());
				tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
				treelist.add(tree);
			}
		}
		return treelist;
	}
	
	/**
	 * 异步加载对象树
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAsyncObjectTreeByPopdom(String fid, boolean isQuery, A_Employee employee, Map<String, List<String>> popdomMap) throws Exception{
		if (employee.isIsadmin())
			return this.getAsyncObjectTree(fid, isQuery, employee);
		
		List<String> branchIds = popdomMap.get(Config.POPEDOMBRANCH);
		List<Tree> treelist = new ArrayList<Tree>();
		boolean isBranch = false;
		for (String id : branchIds) {
			if (id.equals(employee.getBranchid())){
				isBranch = true;
				break;
			}
		}
		if (!isBranch){
			A_Branch eBranch = this.get(employee.getBranchid());
			if (eBranch != null){
				if (eBranch.getStatuscode().equals(jgztqy1) || isQuery){
					Tree tree = new Tree();
					tree.setId(eBranch.getId());
					tree.setText(eBranch.getName());
					tree.setLeaf(true);
					treelist.add(tree);
				}
			}
		}
		A_Branch branch = this.getObjectStructByID(fid, employee.getCompanyid());
		if (branch != null && branch.getList() != null && branch.getList().size() > 0){
			Tree tree = null;
			A_Branch obj = null;
			boolean flage = false;
			for (Object o : branch.getList()) {
				obj = (A_Branch)o;
				if (!isQuery && !obj.getStatuscode().equals(jgztqy1))
					continue;
				flage = false;
				for (String sid : branchIds) {
					if (obj.getId().equals(sid)){
						flage = true;
						break;
					}
				}
				if (!flage)
					continue;
				tree = new Tree();
				tree.setId(obj.getId());
				tree.setText(obj.getName());
				tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
				treelist.add(tree);
			}
		}
		return treelist;
	}
	
	/**
	 * 一次性加载部门树，根据权限加载
	 * @return
	 * @throws Exception
	 */
	public List<Tree> getAllObjectTreeByPopdom(ParametersUtil param, boolean isQuery, A_LoginInfo login) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		//不是管理员加载人员所属部门
		if (!login.getEmployee().isIsadmin()){
			List<String> branchIds = login.getPopedomMap().get(Config.POPEDOMBRANCH);
			boolean isBranch = false;
			for (String id : branchIds) {
				if (id.equals(login.getEmployee().getBranchid())){
					isBranch = true;
					break;
				}
			}
			if (!isBranch){
				A_Branch eBranch = this.get(login.getEmployee().getBranchid());
				if (eBranch != null){
					if (eBranch.getStatuscode().equals(jgztqy1) || isQuery){
						Tree tree = new Tree();
						tree.setId(eBranch.getId());
						tree.setText(eBranch.getName());
						tree.setLeaf(true);
						treelist.add(tree);
					}
				}
			}
		}
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				A_Branch branch = this.getObjectStructByID(objectMap.get("fid").toString(), login.getEmployee().getCompanyid());
				if (branch != null && branch.getList() != null && branch.getList().size() > 0){
					treelist.addAll(this.getObjectTree(objectMap.get("fid").toString(), branch.getList(), 
							login.getPopedomMap().get(Config.POPEDOMBRANCH), 
							login.getEmployee().getBranchid(),
							login.getEmployee().isIsadmin(),
							isQuery));
				}
			}
		}
		return treelist;
	}
	private List<Tree> getObjectTree(String fid, List<Object> list, List<String> branchPop, 
			String branchID, boolean isAdmin, boolean isQuery) throws Exception{
		List<Tree> treelist = new ArrayList<Tree>();
		Tree node = null;
		A_Branch obj = null;
		for (Object o : list) {
			obj = (A_Branch)o;
			if (!isQuery && !obj.getStatuscode().equals(jgztqy1))
				continue;
			if (isAdmin || branchPop.indexOf(obj.getId()) != -1 || obj.getId().equals(branchID)){
				if (obj.getParentid().equals(fid)){
					node = new Tree();
					node.setId(obj.getId());
					node.setText(obj.getName());
					node.setLeaf(Boolean.valueOf(obj.getIsleaf()));
					if(!node.isLeaf()){
						node.setExpanded(true);
						node.setChildren(this.getObjectTree(obj.getId(), obj.getList(), 
								branchPop, branchID, isAdmin, isQuery));
					}
					treelist.add(node);
				}
			}
		}
		return treelist;
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 */
	public void saveObject(A_Branch obj , A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			A_Branch obj_old = objectDao.get(obj.getId());
			String name = obj_old.getName();
			obj_old.setParentid(obj.getParentid());
			obj_old.setParentname(obj.getParentname());
			obj_old.setCode(obj.getCode());
			obj_old.setName(obj.getName());
			obj_old.setSort(obj.getSort());
			obj_old.setRemark(obj.getRemark());
			obj_old.setTelephone(obj.getTelephone());
			obj_old.setAddress(obj.getAddress());
			obj_old.setUpdatedate(this.getData());//设置修改日期
			obj_old.setUpdateemployeeid(employee.getId());//设置修改用户id
			obj_old.setUpdateemployeename(employee.getRealname());//设置修改用户姓名
			obj_old.setStatuscode(jgztty1);
			obj_old.setStatusname(jgztty2);
			objectDao.update(obj_old);
			if (!name.equals(obj_old.getName())){
				this.employeeService.updateBranchName(obj_old.getId(), obj_old.getName());
			}
		}else{
			//添加
			obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());
			obj.setCompanyname(employee.getCompanyname());
			obj.setAdddate(this.getData());//设置添加日期
			obj.setAddemployeeid(employee.getId());//设置添加用户id
			obj.setAddemployeename(employee.getRealname());//设置添加用户姓名
			obj.setIsleaf("true");
			obj.setStatuscode(jgztty1);
			obj.setStatusname(jgztty2);
			obj.setDeleted("0");//设置删除标志(0:正常 1：已删除)
			objectDao.save(obj);
			objectDao.executeHql("update A_Branch t set t.isleaf = 'false' where t.id = '" + obj.getParentid() + "'");
		}
		EhcacheUtil.getInstance().remove(Config.BRANCHMAP + employee.getCompanyid());
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, A_BranchServiceImpl.class);
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		String oid = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
			oid = id;
		}
		objectDao.executeHql("update A_Branch t set t.deleted = '1' where t.id in (" + ids + ")");
		A_Branch obj = objectDao.get(oid);
		if (obj != null){
			objectDao.executeHql("update A_Branch t set t.isleaf = '" + this.checkLeaf(obj.getParentid()) + "' where t.id = '" + obj.getParentid() + "'");
		}
		EhcacheUtil.getInstance().remove(Config.BRANCHMAP + obj.getCompanyid());
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public A_Branch getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		A_Branch obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}


	/**
	 * 获取权限树
	 * @param parameters
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	public List<CheckTree> getAllQxObjectCheck(ParametersUtil parameters, A_Employee employee) throws Exception{
		List<CheckTree> menulist = new ArrayList<CheckTree>();
		List<Object> list = this.getObjectStructByID(
				employee.getCompanyid(), employee.getCompanyid()).getList();
		if (list == null || list.size() == 0)
			return menulist;
		CheckTree tree = null;
		A_Branch obj = null;
		for (Object object : list) {
			obj = (A_Branch) object;
			if (!obj.getStatuscode().equals(jgztqy1))
				continue;
			tree = new CheckTree();
			tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getName());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTreeStruct(tree, obj.getList());
			menulist.add(tree);
		}
		return menulist;
	}

	/**
	 * 获得复选框权限结构
	 * @param fTree
	 * @param list
	 */
	private void getCheckTreeStruct(CheckTree fTree, List<Object> list){
		fTree.setLeaf(true);
		if (list == null && list.size() == 0){
			return;
		}
		CheckTree tree = null;
		A_Branch obj = null;
		for (Object object : list) {
			obj = (A_Branch) object;
			if (!obj.getStatuscode().equals(jgztqy1))
				continue;
			fTree.setLeaf(false);
			tree = new CheckTree();
			tree.setChecked(false);
			tree.setId(obj.getId());
			tree.setText(obj.getName());
			tree.setLeaf(Boolean.valueOf(obj.getIsleaf()));
			this.getCheckTreeStruct(tree , obj.getList());
			fTree.getChildren().add(tree);
		}
	}
	
	/**
	 * 加载部门数据列表
	 * @return
	 * @throws Exception
	 */
	public List<A_Branch> getObjectList() throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		return objectDao.getList(c);
	}
	
	/**
	 * 获取部门及包含下级所有部门ID集合
	 * @return
	 * @throws Exception
	 */
	public List<String> getObjectStructIDList(String id, String companyID) throws Exception{
		List<String> idList = new ArrayList<String>();
		A_Branch branch = this.getObjectStructByID(id, companyID);
		if (branch == null)
			return idList;
		idList.add(branch.getId());
		this.getObjectStructID(idList, branch.getList());
		return idList;
	}
	private void getObjectStructID(List<String> idList, List<Object> objList){
		if (objList == null && objList.size() == 0)
			return;
		A_Branch branch = null;
		for (Object object : objList) {
			branch = (A_Branch)object;
			idList.add(branch.getId());
			this.getObjectStructID(idList, branch.getList());
		}
	}
	
	/**
	 * 修改状态
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateEnabledObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		if (isEnabled){
			objectDao.executeHql("update A_Branch t set t.statuscode = '" + jgztqy1 + "', t.statusname = '启用', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + " 修改“启用” " + ids, employee, A_BranchServiceImpl.class);
		}else{
			objectDao.executeHql("update A_Branch t set t.statuscode = '" + jgztty1 + "', t.statusname = '停用', t.updatedate = '" + this.getData() + 
				"', t.updateemployeeid = '" + employee.getId() + "', t.updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
			this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + " 修改“停用” " + ids, employee, A_BranchServiceImpl.class);
		}
		EhcacheUtil.getInstance().remove(Config.BRANCHMAP + employee.getCompanyid());
	}

	/**
	 * 院系数据和统一身份认证同步
	 * @throws Exception
	 */
	public void updateSyncBranch(A_Employee employee) throws Exception{
		LDAPAuthentication ldap = new LDAPAuthentication();
		try{
			ldap.LDAP_connect();
		}catch (Exception e){
			throw new BusinessException("统一身份认证接口连接失败，请联系管理员");
		}
		List<Map<String, String>> list = ldap.getTeacherList();
		List<String> newList = new ArrayList<>();
		for (Map<String, String> stringStringMap : list) {
			String yx = stringStringMap.get("yx");
			if(!checkBranch(newList, yx)){
				newList.add(yx);
			}
		}
		for (int i = 0; i < newList.size(); i++) {
			String branchName = newList.get(i);
			A_Branch branch = new A_Branch();
			branch.setId(this.getUUID());//设置主键
			branch.setParentid("FSDCOMPANY");
			branch.setParentname("兰州工业学院");
			branch.setCode("JG-" + (i+1));
			branch.setName(branchName);
			branch.setCompanyid(employee.getCompanyid());
			branch.setCompanyname(employee.getCompanyname());
			branch.setAdddate(this.getData());
			branch.setAddemployeeid(employee.getId());
			branch.setAddemployeename(employee.getRealname());
			branch.setIsleaf("true");
			branch.setStatuscode(jgztqy1);
			branch.setStatusname(jgztqy2);
			branch.setSort(Long.valueOf(i+1));
			branch.setDeleted("0");
			objectDao.save(branch);
		}
		EhcacheUtil.getInstance().remove(Config.BRANCHMAP + employee.getCompanyid());
	}

	private boolean checkBranch(List<String> list, String branch){
		for (String branchName : list) {
			if(branchName.equals(branch)){
				return true;
			}
		}
		return false;
	}
}
